package factorytest.iflytek.com.einkiflytekfactorytest.iflytekWakeup;


import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvent;
import com.iflytek.cloud.VoiceWakeuper;
import com.iflytek.cloud.WakeuperListener;
import com.iflytek.cloud.WakeuperResult;
import com.iflytek.cloud.util.ResourceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.SystemPropertyUtil;

public class HtfyunWakeupEngine {

    private final String IVW_AUDIO_PATH = Environment.getExternalStorageDirectory().getPath() + "/msc/ivw.wav";
    private final String PROPERTY_THRESH = "persist.wakeup.thresh";

    private final Context mContext;

    private final static int MAX = 3000;
    private final static int MIN = 0;
    private int DEFAULT_WAKEUP_THRESH_VALUE = 1450;//唤醒门限值
    private final int curThresh;
    private String keep_alive = "1";
    private String ivwNetMode = "0";


    private HtfyunWakeuperListener htfyunWakeuperListener;

    public HtfyunWakeupEngine(Context context) {
        mContext = context;

        String valueStr = SystemPropertyUtil.getSystemProperty(PROPERTY_THRESH);
        if (!TextUtils.isEmpty(valueStr) && TextUtils.isDigitsOnly(valueStr)) {
            curThresh = Integer.decode(valueStr);
        } else {
            curThresh = DEFAULT_WAKEUP_THRESH_VALUE;
        }
    }

    public void setHtfyunWakeuperListener(HtfyunWakeuperListener htfyunWakeuperListener) {
        this.htfyunWakeuperListener = htfyunWakeuperListener;
    }

    private VoiceWakeuper getWakeuper() {
        VoiceWakeuper vw = VoiceWakeuper.getWakeuper();
        if (vw == null) {
            vw = VoiceWakeuper.createWakeuper(mContext, null);
        }
        return vw;
    }

    public void start() {
        VoiceWakeuper mIvw = getWakeuper();
        // 清空参数
        mIvw.setParameter(SpeechConstant.PARAMS, null);
        // 唤醒门限值，根据资源携带的唤醒词个数按照“id:门限;id:门限”的格式传入
        mIvw.setParameter(SpeechConstant.IVW_THRESHOLD, "0:"+ curThresh);
        // 设置唤醒模式
        mIvw.setParameter(SpeechConstant.IVW_SST, "wakeup");
        // 设置持续进行唤醒
        mIvw.setParameter(SpeechConstant.KEEP_ALIVE, keep_alive);
        // 设置闭环优化网络模式
        mIvw.setParameter(SpeechConstant.IVW_NET_MODE, ivwNetMode);
        // 设置唤醒资源路径
        mIvw.setParameter(SpeechConstant.IVW_RES_PATH, getResource());
        // 设置唤醒录音保存路径，保存最近一分钟的音频
        mIvw.setParameter( SpeechConstant.IVW_AUDIO_PATH, IVW_AUDIO_PATH );
        mIvw.setParameter( SpeechConstant.AUDIO_FORMAT, "wav" );
        // 如有需要，设置 NOTIFY_RECORD_DATA 以实时通过 onEvent 返回录音音频流字节
        //mIvw.setParameter( SpeechConstant.NOTIFY_RECORD_DATA, "1" );
        // 启动唤醒
        /*	mIvw.setParameter(SpeechConstant.AUDIO_SOURCE, "-1");*/

        mIvw.startListening(mWakeuperListener);
    }

    public void stop() {
        getWakeuper().stopListening();
    }

    public void destroy() {
        DebugLog.e("onDestroy WakeDemo");
        // 销毁合成对象
        VoiceWakeuper mIvw = VoiceWakeuper.getWakeuper();
        if (mIvw != null) {
            mIvw.destroy();
        }
    }

    private String getResource() {
        final String resPath = ResourceUtil.generateResourcePath(mContext, ResourceUtil.RESOURCE_TYPE.assets,
                "ivw/" + mContext.getString(R.string.app_id) + ".jet");
        DebugLog.e("resPath: " + resPath);
        return resPath;
    }

    private WakeuperListener mWakeuperListener = new WakeuperListener() {

        @Override
        public void onResult(WakeuperResult result) {

            String resultString = "";
            try {
                String text = result.getResultString();
                DebugLog.e("--->> onResult result.getResultString()=" + text);

                JSONObject object;
                object = new JSONObject(text);
                StringBuffer buffer = new StringBuffer();
                buffer.append("【RAW】 "+text);
                buffer.append("\n");
                buffer.append("【操作类型】"+ object.optString("sst"));
                buffer.append("\n");
                buffer.append("【唤醒词id】"+ object.optString("id"));
                buffer.append("\n");
                buffer.append("【得分】" + object.optString("score"));
                buffer.append("\n");
                buffer.append("【前端点】" + object.optString("bos"));
                buffer.append("\n");
                buffer.append("【尾端点】" + object.optString("eos"));
                resultString =buffer.toString();

                int score = object.optInt("score");
                if (score >= curThresh) {
                    DebugLog.e("===================== wake up ================");
                    if (htfyunWakeuperListener != null) {
                        htfyunWakeuperListener.onWakeUp(object.toString());
                    }
                }

            } catch (JSONException e) {
                resultString = "唤醒结果解析出错";
                e.printStackTrace();
                if (htfyunWakeuperListener != null) {
                    htfyunWakeuperListener.onError(resultString);
                }
            }

            DebugLog.e(resultString);

        }

        @Override
        public void onError(SpeechError error) {
            DebugLog.e(error.getPlainDescription(true));
            if (htfyunWakeuperListener != null) {
                htfyunWakeuperListener.onError(error.getPlainDescription(true));
            }
        }

        @Override
        public void onBeginOfSpeech() {
        }

        @Override
        public void onEvent(int eventType, int isLast, int arg2, Bundle obj) {
           /* switch( eventType ){
                // EVENT_RECORD_DATA 事件仅在 NOTIFY_RECORD_DATA 参数值为 真 时返回
                case SpeechEvent.EVENT_RECORD_DATA:
                    final byte[] audio = obj.getByteArray( SpeechEvent.KEY_EVENT_RECORD_DATA );
                    DebugLog.e("ivw audio length: " + audio.length);
                    break;
            }*/
        }

        @Override
        public void onVolumeChanged(int volume) {

        }
    };
}
